﻿/// <reference path="~/Scripts/Library/jquery-1.9.1.min.js" />

/// <reference path="~/Scripts/Application/Physis_jqGridSupport.js" />

var postbackController = "SecurityManagement";

function ConfigurationItem_Validate() {

    var isValid = true;

    var lastResponseMessageLabel = $("#LastResponseMessageLabel");


    // SERIALIZE THE SELECTED PERMISSIONS TO JSON 

    for (var currentIndex = 0; currentIndex < rolePermissionsAvailable.length; currentIndex++) {

        rolePermissionsAvailable[currentIndex].Granted = $("#" + (currentIndex + 1) + "_Granted")[0].checked;

        rolePermissionsAvailable[currentIndex].Denied = $("#" + (currentIndex + 1) + "_Denied")[0].checked;

    }


    $("#RolePermissions").val(JSON.stringify(rolePermissionsAvailable));

    $("#RoleMembership").val(JSON.stringify(roleMembership));


    return isValid;

}

function ConfigurationItem_OnReady() {

    // MEMBERSHIP 

    $("#PropertyTabs li a")[2].click(); // SELECT MEMBERSHIP TAB     
    
    ProgressBar_AjaxUnder_Initialize("Membership_UserAccountSelection_ProgressBar");

    MembershipGrid_Initialize();

    Membership_SecurityAuthoritySelection_OnChange();


    // PERMISSIONS

    $("#PropertyTabs li a")[1].click(); // SELECT PERMISSIONS TAB 

    PermissionsGrid_Initialize();


    // GENERAL

    $("#PropertyTabs li a")[0].click(); // SELECT GENERAL TAB 
    
}


// PERMISSIONS 

function PermissionsGrid_Initialize() {

    $("#PermissionsGrid").jqGrid({

        width: 0,

        height: 375,

        datatype: "local",

        data: rolePermissionsAvailable,

        rowNum: 99999,

        colModel:

            [

                { name: "PermissionId", label: "Id", width: 80, fixed: true, sortable: false, search: false },

                { name: "Name", label: "Name" },

                { name: "Granted", label: "Is Granted", width: 80, fixed: true, align: "center", editable: true, edittype: "checkbox", editoptions: { value: "true:false" }, search: false },

                { name: "Denied", label: "Is Denied", width: 80, fixed: true, align: "center", editable: true, edittype: "checkbox", editoptions: { value: "true:false" }, search: false }


            ],

        loadComplete: function () {

            for (var currentIndex = 0; currentIndex < this.rows.length; currentIndex++) {

                currentRow = this.rows[currentIndex];

                $(this).jqGrid("editRow", currentRow.id, true);

            }

        }

    });

    $("#PermissionsGrid").jqGrid("filterToolbar", { searchOnEnter: true });

    jqGrid_RemoveCorners("PermissionsGrid");

    jqGrid_ResizeToFitWidth("PermissionsGrid");

}


// MEMBERSHIP 

function MembershipGrid_Formatters_Action(cellValue, options, rowObject) {

    return "<a href=\"javascript:void(0);\" onclick=\"MembershipGrid_Remove_OnClick(this);\">(remove)</a>";

}

function MembershipGrid_Initialize() {

    $("#MembershipGrid").jqGrid({

        width: 0,

        height: 300,

        datatype: "local",

        data: roleMembership,

        rowNum: 99999,

        colModel: [

                { name: "UserAccountId", label: "Id", width: 80, fixed: true, sortable: false, search: false },

                { name: "SecurityAuthorityName", label: "Security Authority" },

                { name: "UserAccountName", label: "User Account Name" },
                
                { name: "Action", width: "80px", align: "center", fixed: true, search: false, formatter: MembershipGrid_Formatters_Action }

            ],

        loadComplete: function () {

            for (var currentIndex = 0; currentIndex < this.rows.length; currentIndex++) {

                currentRow = this.rows[currentIndex];

                $(this).jqGrid("editRow", currentRow.id, true);

            }

        }

    });

    $("#MembershipGrid").jqGrid("filterToolbar", { searchOnEnter: true });

    jqGrid_RemoveCorners("MembershipGrid");

    jqGrid_ResizeToFitWidth("MembershipGrid");

}

function RoleMembership_ContainsUserAccount(userAccountId) {

    for (var currentIndex = 0; currentIndex < roleMembership.length; currentIndex++) {

        if (roleMembership[currentIndex].UserAccountId == userAccountId) { return true; }

    }

    return false;

}

function MembershipGrid_Remove_OnClick(sender) {

    var tableRow = $(sender).closest("tr");

    if (tableRow.length > 0) {

        dataRowId = tableRow[0].id;

        var securityAuthorityName = $("#MembershipGrid").jqGrid("getCell", dataRowId, "SecurityAuthorityName");

        var userAccountName = $("#MembershipGrid").jqGrid("getCell", dataRowId, "UserAccountName");
        
        Membership_Remove(securityAuthorityName, userAccountName);

        $("#MembershipGrid").jqGrid("delRowData", dataRowId);

        Membership_SecurityAuthoritySelection_OnChange();

    }

}

function MembershipGrid_Refresh() {

    $("#MembershipGrid").jqGrid().GridUnload();

    MembershipGrid_Initialize();

}


function Membership_SecurityAuthoritySelection_OnChange() {

    $("#Membership_UserAccountSelection").empty();

    $("#Membership_UserAccountSelection").append($("<option value=\"\">Loading ...</option>"));

    ProgressBar_AjaxUnder_On("Membership_UserAccountSelection");

    $("#Membership_UserAccountAdd").hide();

    var requestUrl = $("#RootUrl").val() + "SecurityManagement/UserAccountsBySecurityAuthority";

    requestUrl += "?SecurityAuthorityId=" + $("#Membership_SecurityAuthoritySelection").val();

    $.ajax({

        url: requestUrl,

        error: function (jqXHR, textStatus, errorThrown) {

            $("#Membership_UserAccountSelection").empty();

            $("#Membership_UserAccountSelection").append($("<option value=\"\">Error: " + errorThrown + "</option>"));

        },

        success: function (response, textStatus, jqXHR) {

            $("#Membership_UserAccountSelection").empty();

            for (var currentIndex = 0; currentIndex < response.Objects.length; currentIndex++) {

                if (!RoleMembership_ContainsUserAccount(response.Objects[currentIndex].Id)) {

                    $("#Membership_UserAccountSelection").append($("<option value=\"" + response.Objects[currentIndex].Id + "\">" + response.Objects[currentIndex].Name + "</option>"));

                }

            }

            if ($("#Membership_UserAccountSelection option").length > 0) {

                $("#Membership_UserAccountAdd").show();

            }

        },

        complete: function () {

            ProgressBar_AjaxUnder_Off("Membership_UserAccountSelection");

        }

    });

}

function Membership_Remove(securityAuthorityName, userAccountName) {

    var removeIndex = -1;

    for (var currentIndex = 0; currentIndex < roleMembership.length; currentIndex++) {

        var membership = roleMembership[currentIndex];

        if ((membership.SecurityAuthorityName == securityAuthorityName) && (membership.UserAccountName == userAccountName)) {

            removeIndex = currentIndex;

            break;

        }

    }

    if (removeIndex >= 0) {

        roleMembership = roleMembership.removeAt(removeIndex);

    }

}

function Membership_UserAccountAdd_OnClick() {

    var securityAuthorityId = $("#Membership_SecurityAuthoritySelection").val();

    var securityAuthorityName = $("#Membership_SecurityAuthoritySelection option[value=" + securityAuthorityId + "]")[0].innerHTML

    var userAccountId = $("#Membership_UserAccountSelection").val();

    var userAccountName = $("#Membership_UserAccountSelection option[value=" + userAccountId + "]")[0].innerHTML


    if (!RoleMembership_ContainsUserAccount(userAccountId)) {

        var roleMembershipEntry = JSON.parse(JSON.stringify(roleMembershipBaseObject));

        roleMembershipEntry.SecurityAuthorityName = securityAuthorityName;

        roleMembershipEntry.UserAccountId = userAccountId;

        roleMembershipEntry.UserAccountName = userAccountName;

        roleMembership.push(roleMembershipEntry);

        MembershipGrid_Refresh();

    }

    Membership_SecurityAuthoritySelection_OnChange();

}